//
//  ONAddSymbolViewController.m
//  Volatix
//
//  Created by Nguyen Minh Duc on 6/5/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//

#import "ONAddSymbolViewController.h"
#import "ONAddSymbolTableViewCell.h"
#import "ONISOModel.h"
#import "ONISOObjects.h"
@interface ONAddSymbolViewController ()<ONAddSymbolTableViewCellDelegate>
@property (nonatomic,strong) ONISOObjects *isParentISO;
@property (nonatomic,strong) ONISOObjects *isParentLoadZone;
@end

@implementation ONAddSymbolViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    self.level = 0;
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.Items = [[NSMutableArray alloc] init];
    [self layoutSectionViewWithLevel:(int)self.level];
    [self prepareData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    
    [self.tableView reloadData];
}


#define kPading 0

-(void)layoutSectionViewWithLevel:(int)level{
    if(level == 0){
        self.selectISOLabel.hidden = NO;
        self.selectLoadZoneLabel.hidden = YES;
        self.selectPowerPointLabel.hidden = YES;
        
        self.loadZoneImageView.hidden = YES;
        self.powerPointImageView.hidden = YES;
        
        
        self.selectISOLabel.text = @"SELECT ISO";
        self.selectISOLabel.font = [UIFont boldSystemFontOfSize:14];
        
        CGRect frIosLabel = self.selectISOLabel.frame;
        frIosLabel.size.width = [self widthForCellWithText:self.selectISOLabel.text andFont:self.selectISOLabel.font];
        self.selectISOLabel.frame = frIosLabel;
        
    }
    
    if(level == 1){
        self.selectPowerPointLabel.hidden = YES;
        self.powerPointImageView.hidden = YES;
        
        self.selectLoadZoneLabel.text = @"SELECT LOAD ZONE";
        self.selectISOLabel.text = self.iso;
        self.selectLoadZoneLabel.font = [UIFont boldSystemFontOfSize:14];
        
        CGRect frIosLabel = self.selectISOLabel.frame;
        frIosLabel.size.width = [self widthForCellWithText:self.selectISOLabel.text andFont:self.selectISOLabel.font];
        self.selectISOLabel.frame = frIosLabel;
        
        CGRect frLoadZoneImageView =  self.loadZoneImageView.frame;
        frLoadZoneImageView.origin.x = kPading + CGRectGetMaxX(frIosLabel);
        self.loadZoneImageView.frame = frLoadZoneImageView;
        
        CGRect frLoadZoneLabel = self.selectLoadZoneLabel.frame;
        frLoadZoneLabel.size.width = [self widthForCellWithText:self.selectLoadZoneLabel.text andFont:self.selectLoadZoneLabel.font];
        frLoadZoneLabel.origin.x = kPading + CGRectGetMaxX(frLoadZoneImageView);
        self.selectLoadZoneLabel.frame = frLoadZoneLabel;
        
    }
    
    if(level == 2){
        self.selectISOLabel.text = self.iso;
        self.selectLoadZoneLabel.text = self.loadZone;
        self.selectPowerPointLabel.text = @"SELECT POWER POINT";
        self.selectPowerPointLabel.font = [UIFont boldSystemFontOfSize:14];
        
        CGRect frIosLabel = self.selectISOLabel.frame;
        frIosLabel.size.width = [self widthForCellWithText:self.selectISOLabel.text andFont:self.selectISOLabel.font];
        self.selectISOLabel.frame = frIosLabel;
        
        CGRect frLoadZoneImageView =  self.loadZoneImageView.frame;
        frLoadZoneImageView.origin.x = kPading + CGRectGetMaxX(frIosLabel);
        self.loadZoneImageView.frame = frLoadZoneImageView;
        
        
        CGRect frLoadZoneLabel = self.selectLoadZoneLabel.frame;
        frLoadZoneLabel.size.width = [self widthForCellWithText:self.selectLoadZoneLabel.text andFont:self.selectLoadZoneLabel.font];
        frLoadZoneLabel.origin.x = kPading + CGRectGetMaxX(frLoadZoneImageView);
        self.selectLoadZoneLabel.frame = frLoadZoneLabel;
        
        
        CGRect frPowerPointImageView =  self.powerPointImageView.frame;
        frPowerPointImageView.origin.x = kPading + CGRectGetMaxX(frLoadZoneLabel);
        self.powerPointImageView.frame = frPowerPointImageView;
        
        
        
        CGRect frPowerPointLabel = self.selectPowerPointLabel.frame;
        frPowerPointLabel.size.width = [self widthForCellWithText:self.selectPowerPointLabel.text andFont:self.selectPowerPointLabel.font];
        frPowerPointLabel.origin.x = kPading + CGRectGetMaxX(frPowerPointImageView);
        self.selectPowerPointLabel.frame = frPowerPointLabel;
        
    }
    
}

- (void)prepareDataForLevel0 {

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
    [params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
    [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_LIST_ISO andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
        ///
        self.dataArray = [[ONISOModel modelObjectWithDictionary:responseObject].objects mutableCopy];
        
        for (ONISOObjects *isoObject  in self.dataArray) {
            
            for (ONISOObjects *realTimeObject in self.addSymbolItemsArray) {
                
                if ([realTimeObject.name isEqualToString:isoObject.name] && realTimeObject.isAdded) {
                    isoObject.isAdded = YES;
                }
            }
        }
        
        [self.tableView reloadData];
    } failureBlock:^(NSError *error) {
        ///
    }];
    
    
}

- (void)prepareDataForLevel1 {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
    [params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
    [params setObject:self.iso forKey:@"ISO"];
    [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_LIST_LOADZONE andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
        ///
        self.dataArray = [NSMutableArray array];
        for (id item in responseObject) {
            ONISOObjects *isoObject = [ONISOObjects modelObjectWithDictionary:item];
            [self.dataArray addObject:isoObject];
            for (ONISOObjects *realTimeObject in self.addSymbolItemsArray) {
                
                if ([realTimeObject.name isEqualToString:isoObject.name] && realTimeObject.isAdded) {
                    isoObject.isAdded = YES;
                }
            }
        }
        
        [self.tableView reloadData];
    } failureBlock:^(NSError *error) {
        ///
    }];
    
    
    
}


- (void)prepareDataForLevel2 {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
    [params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
    [params setObject:self.iso forKey:@"ISO"];
    [params setObject:self.loadZone forKey:@"LOADZONE"];
    [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_LIST_POWERPOINT andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
        ///
        self.dataArray = [NSMutableArray array];
        for (id item in responseObject) {
            ONISOObjects *isoObject = [ONISOObjects modelObjectWithDictionary:item];
            [self.dataArray  addObject:isoObject];
            
            for (ONISOObjects *realTimeObject in self.addSymbolItemsArray) {
                if ([realTimeObject.name isEqualToString:isoObject.name] && realTimeObject.isAdded) {
                    isoObject.isAdded = YES;
                }
            }
        }
        
        [self.tableView reloadData];
    } failureBlock:^(NSError *error) {
        ///
    }];
}

-(void)prepareData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    UIBarButtonItem *_btn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_done.png"]
                                                          style:UIBarButtonItemStylePlain
                                                         target:self
                                                         action:@selector(doneDidSelected:)];
    self.navigationItem.rightBarButtonItem=_btn;
    
    if(self.level == 0){
        
       
        
        UIBarButtonItem *_btn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow_left.png"]
                                                              style:UIBarButtonItemStylePlain
                                                             target:self
                                                             action:@selector(cancelButtonPressed:)];
        self.navigationItem.leftBarButtonItem=_btn;
        [self prepareDataForLevel0];
    }
    
    if(self.level == 1){
        UIBarButtonItem *_btn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow_left.png"]
                                                              style:UIBarButtonItemStylePlain
                                                             target:self
                                                             action:@selector(cancelPopView:)];
        
        self.navigationItem.leftBarButtonItem=_btn;
        [self prepareDataForLevel1];
    }

    if(self.level == 2){
        UIBarButtonItem *_btn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow_left.png"]
                                                              style:UIBarButtonItemStylePlain
                                                             target:self
                                                             action:@selector(cancelPopView:)];
        
        self.navigationItem.leftBarButtonItem=_btn;
        [self prepareDataForLevel2];
        
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger numberOfCell = [self.dataArray count];

    return numberOfCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *identifierString = @"ONAddSymbolTableViewCell";
    ONAddSymbolTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierString];
    if(cell == nil){
        cell = [[ONAddSymbolTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierString];
    }
    
        cell.indexPath = indexPath;
        cell.tableView = tableView;
    
        ONISOObjects *oNISOObject = [self.dataArray objectAtIndex:indexPath.row];
        [cell loadCellData:oNISOObject];
        [cell setDelegate:self];
        if([self.Items containsObject:oNISOObject]){
            [cell cellWillSelect:YES];
        }
       // NSLog(@"oNISOObject.name %@",oNISOObject.name);

    return cell;
}
-(BOOL) checkingExitBy:(ONISOObjects *)iSOObject and:(NSMutableArray *)array
{
   
    for (ONISOObjects *realTimeObject in array) {
        if ([realTimeObject.name isEqualToString:iSOObject.name]) {
            return YES;;
        }
    }
    
    
    return false;
}
-(void)ONAddSymbolTableViewCellDidselected:(ONISOObjects *)iSOObject{
    
    iSOObject.isAdded = YES;
    if (![self checkingExitBy:iSOObject and:self.addSymbolItemsArray]) {
        
        switch (self.level) {
            case 0:
                //
                iSOObject.type=LEVEL_ISO;
                iSOObject.iso =nil;
                iSOObject.loadZone=nil;
                break;
            case 1:
                //
                iSOObject.type=LEVEL_LOADZONE;
                iSOObject.iso =self.iso;
                iSOObject.loadZone=nil;
                /// Add More Object Parrent if not exit
                if(self.isParentISO!=nil)
                {
                    
                    if(![self checkingExitBy:self.isParentISO and:self.addSymbolItemsArray])
                    {
                        self.isParentISO.iso =self.iso;
                        self.isParentISO.type = LEVEL_ISO;
                        self.isParentISO.isAdded=YES;
                        [self.addSymbolItemsArray addObject:self.isParentISO];
                    }
                    if(![self checkingExitBy:self.isParentISO and:self.Items])
                    {
                        self.isParentISO.iso =self.iso;
                        self.isParentISO.type = LEVEL_ISO;
                        self.isParentISO.isAdded=YES;
                        [self.Items addObject:self.isParentISO];
                    }
                    

                }
                
                
                break;
            case 2:
                //
                iSOObject.type=LEVEL_POWERPOINT;
                iSOObject.iso =self.iso;
                iSOObject.loadZone=self.loadZone;
                /// Add More two Object Parrent if not exit
                if(self.isParentISO!=nil)
                {
                    if(![self checkingExitBy:self.isParentISO and:self.addSymbolItemsArray])
                    {
                        self.isParentISO.iso =self.iso;
                        self.isParentISO.type = LEVEL_ISO;
                        self.isParentISO.isAdded=YES;
                        [self.addSymbolItemsArray addObject:self.isParentISO];
                    }
                    if(![self checkingExitBy:self.isParentISO and:self.Items])
                    {
                        self.isParentISO.iso =self.iso;
                        self.isParentISO.type = LEVEL_ISO;
                        self.isParentISO.isAdded=YES;
                        [self.Items addObject:self.isParentISO];
                    }

                    
                }
                /// loadzone
                if(self.isParentLoadZone!=nil)
                {
                    if(![self checkingExitBy:self.isParentLoadZone and:self.addSymbolItemsArray])
                    {
                        self.isParentLoadZone.iso =self.iso;
                        self.isParentLoadZone.loadZone =self.loadZone;
                        self.isParentLoadZone.type = LEVEL_LOADZONE;
                        self.isParentLoadZone.isAdded=YES;
                        [self.addSymbolItemsArray addObject:self.isParentLoadZone];
                    }
                    if(![self checkingExitBy:self.isParentLoadZone and:self.Items])
                    {
                        self.isParentLoadZone.iso =self.iso;
                        self.isParentLoadZone.loadZone =self.loadZone;
                        self.isParentLoadZone.type = LEVEL_LOADZONE;
                        self.isParentLoadZone.isAdded=YES;
                        [self.Items addObject:self.isParentLoadZone];
                    }

                    
                }
                
                
                break;
            default:
                break;
        }
        
        NSLog(@"Level %ld parrentName = %@ grandParent =%@ ",(long)iSOObject.type,iSOObject.iso,iSOObject.loadZone);
        
         [self.addSymbolItemsArray addObject:iSOObject];
    }
    
    
    if(![self.Items containsObject:iSOObject]){
        [self.Items addObject:iSOObject];
    }
}

-(void)ONAddSymbolTableViewCellDidRemoved:(ONISOObjects *)iSOObject{
    
    iSOObject.isAdded = NO;
    
    BOOL exist = NO;
    ONISOObjects *currentObject;
    for (ONISOObjects *realTimeObject in self.addSymbolItemsArray) {
        if ([realTimeObject.name isEqualToString:iSOObject.name]) {
            currentObject = realTimeObject;
            exist = YES;
        }
    }
    
    if (exist) {
        [self.addSymbolItemsArray removeObject:currentObject];
    }

    if([self.Items containsObject:iSOObject]){
        [self.Items removeObject:iSOObject];
    }
}

- (void)oNAddSymbolTableViewCelldidSelectObject:(ONISOObjects *)iSOObject{
    if(self.level == 2) return;
    
    
    // Deselect the row
    
    ONAddSymbolViewController *onAddSymbolViewController = (ONAddSymbolViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ONAddSymbolViewController_new"];//ONAddSymbolViewController
    
    
    if(self.level == 0){
        onAddSymbolViewController.iso = iSOObject.name;
        // more
        onAddSymbolViewController.isParentISO = iSOObject;
        
    }
    
    if(self.level == 1){
        onAddSymbolViewController.iso = self.iso;
        onAddSymbolViewController.loadZone = iSOObject.name;
        /// more
        onAddSymbolViewController.isParentISO =self.isParentISO;
        onAddSymbolViewController.isParentLoadZone = iSOObject;
    }
    onAddSymbolViewController.level = self.level + 1;
    onAddSymbolViewController.typeScreen =self.typeScreen;
    onAddSymbolViewController.addSymbolItemsArray = self.addSymbolItemsArray;
    
    [self.navigationController pushViewController:onAddSymbolViewController animated:YES];
}

#pragma mark - UITableViewDelegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    
}
-(void)cancelPopView:(id)sender
{
    [self.navigationController popViewControllerAnimated:true];
}


- (IBAction)cancelButtonPressed:(id)sender {
    
    [self.addSymbolItemsArray removeAllObjects];
    for (ONISOObjects *object in self.currentRealTimeData) {
        [self.addSymbolItemsArray addObject:object];
    }
    //[[NSNotificationCenter defaultCenter] postNotificationName:SAVING_DATA_REAL_TIME object:nil userInfo:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)doneDidSelected:(id)sender {
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:(_typeScreen==0)?SAVING_DATA_REAL_TIME:(_typeScreen==1)?SAVING_DATA_DAY_AHEAD:SAVING_DATA_ALERT object:nil userInfo:nil];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (CGFloat)widthForCellWithText:(NSString *)text  andFont:(UIFont*)font{
    static CGFloat padding = 0.0;
    
    //UIFont *systemFont = [UIFont systemFontOfSize:14];
    UIFont *systemFont = font;
    CGSize textSize = CGSizeMake(CGFLOAT_MAX, 21);
    CGSize sizeWithFont = [text sizeWithFont:systemFont constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
    
#if defined(__LP64__) && __LP64__
    return ceil(sizeWithFont.width) + padding;
#else
    return ceilf(sizeWithFont.width) + padding;
#endif
}

@end
